package com.file_io;

import java.io.*;

public class IO {
    public static void main(String[] args)  {
       File file=new File("test.txt");
        try {
            if(!file.exists())
                file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String str="hello word!";
        byte[] byte1=str.getBytes();
        FileOutputStream fileOutputStream=null;
        try {
            fileOutputStream=new FileOutputStream(file);
            fileOutputStream.write(byte1);
            fileOutputStream.flush();
            System.out.println("文件写入成功！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
                fileOutputStream = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        FileInputStream fileInputStream=null;

        try {
            fileInputStream=new FileInputStream(file);
            byte[] b = new byte[1024];
            int x = 0;
            while ((x=fileInputStream.read(b))!=-1){
                System.out.println(x);
                String str2  = new String(b);
                System.out.println(str2);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                fileInputStream = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
